#include "memorywidget.h"
#include "ui_memorywidget.h"
#include "memoryitemmodel.h"
#include "memory.h"
#include "cpu.h"
#include "breakpointtable.h"
#include <QModelIndexList>

MemoryWidget::MemoryWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MemoryWidget)
{
    ui->setupUi(this);
    model = new MemoryItemModel(this);
    ui->memoryTable->setModel(model);
    ui->memoryTable->resizeColumnsToContents();
    connect(ui->memoryTable, SIGNAL(doubleClicked(QModelIndex)), model, SLOT(changeBreakPoint(QModelIndex)));
}

quint32 MemoryWidget::selectedPC() const
{
    QModelIndex index = ui->memoryTable->currentIndex();
    if(index.isValid())
    {
        return index.row() * 4 + model->getBaseAddress();
    }
    else
    {
        return CPU::getInstance()->getPC();
    }
}

MemoryWidget::~MemoryWidget()
{
    delete ui;
}

void MemoryWidget::on_pageGo_clicked()
{
    QString text = ui->pageText->text();
    quint32 index = text.toInt();
    model->setPageIndex(index);
}

void MemoryWidget::on_addressGo_clicked()
{
    QString text = ui->addressText->text();
    bool ok;
    quint32 address = text.toLongLong(&ok, 16);
    goToAddress(address);
}

void MemoryWidget::goToAddress(quint32 address) const
{
    quint32 pageIndex = address / 4 / MemoryItemModel::NUMBER_PER_PAGE;
    quint32 index = ((address) % (MemoryItemModel::NUMBER_PER_PAGE * 4)) / 4;
    model->setPageIndex(pageIndex);
    ui->memoryTable->scrollTo(model->index(index, 0), QAbstractItemView::PositionAtCenter);
    ui->memoryTable->selectRow(index);
}
